﻿/* Copyright (C) 2012 by John Cronin
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:

 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.

 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace davserv
{
    class Auth
    {
        static Dictionary<string, IAuthProvider> auth_providers = new Dictionary<string, IAuthProvider>();

        static Auth()
        {
            foreach (Type T in typeof(Auth).Assembly.GetTypes())
            {
                foreach (Type I in T.GetInterfaces())
                {
                    if (I == typeof(Auth.IAuthProvider))
                    {
                        IAuthProvider iap = T.GetConstructor(System.Type.EmptyTypes).Invoke(null) as IAuthProvider;
                        auth_providers[T.Name] = iap;
                    }
                }
            }
        }

        internal static IAuthProvider GetAuthProvider(string name)
        {
            if (auth_providers.ContainsKey(name))
                return auth_providers[name];
            throw new Exception("Unknown authorization provider: " + name);
        }

        public interface IAuthProvider
        {
            string GetHA1Hash(string username, string realm);
            string[] GetGroups(string username, string realm);
            void Init(string init_string);
            bool SetPassword(string username, string realm, string old_pass, string new_pass);
            bool SetGroups(string username, string realm, string[] groups);
            bool DeleteUser(string username, string realm);
        }

        internal static string ComputeMD5Hash(string input)
        {
            System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
            byte[] data = md5.ComputeHash(System.Text.Encoding.Default.GetBytes(input));
            StringBuilder sb = new StringBuilder();
            foreach (byte b in data)
                sb.Append(b.ToString("x2"));
            return sb.ToString();
        }

        internal static bool VerifyMD5Hash(string input, string hash)
        {
            return IgnoreCaseCompare(hash, ComputeMD5Hash(input));
        }

        internal static bool IgnoreCaseCompare(string a, string b)
        {
            if (StringComparer.OrdinalIgnoreCase.Compare(a, b) == 0)
                return true;
            return false;
        }

        internal class AuthHeader
        {
            public string AuthType;
            public Dictionary<string, string> Headers = new Dictionary<string, string>();

            internal static string[] KnownTypes = new string[] { "Digest", "Basic" };
        }

        internal static AuthHeader DecodeAuthorizationHeader(string header)
        {
            AuthHeader ret = new AuthHeader();

            foreach (string atype in AuthHeader.KnownTypes)
            {
                if (header.StartsWith(atype + " "))
                {
                    ret.AuthType = atype;
                    header = header.Substring((atype + " ").Length);
                    break;
                }
            }
            if (ret.AuthType == null)
                throw new Exception("Unknown authorization type: " + header);

            string[] entries = header.Split(',');
            foreach (string entry in entries)
            {
                int equals = entry.IndexOf('=');
                if(equals == -1)
                    throw new Exception("Unknown authorization header entry: " + entry);

                string name = entry.Substring(0, equals).Trim();
                string val = entry.Substring(equals + 1).Trim('\"', ' ');

                ret.Headers.Add(name, val);
            }

            return ret;
        }
    }
}
